const isWin = () => {
  if ((navigator as any).userAgentData) {
    return (navigator as any).userAgentData.platform === "Windows";
  }
  if (navigator.platform) {
    return navigator.platform.toLowerCase() === "win32";
  }
  return navigator.userAgent.indexOf("Windows") !== -1;
};

class Path {
  static readonly isWindows = isWin();
  static readonly sep = isWin() ? "\\" : "/";
  static readonly delimiter = isWin() ? ";" : ":";

  // 获取文件扩展名
  static extname(path: string): string {
    const idx = path.lastIndexOf(".");
    if (idx === -1) return "";
    return path.substring(idx);
  }

  // 获取文件名
  static basename(path: string, ext?: string): string {
    let base = path.split(/[\\/]/).pop() || "";
    if (ext && base.endsWith(ext)) {
      base = base.slice(0, -ext.length);
    }
    return base;
  }

  // 获取目录名
  static dirname(path: string): string {
    const parts = path.split(/[\\/]/);
    parts.pop();
    return parts.join(Path.sep);
  }

  // 连接路径
  static join(...paths: (string | null | undefined | false)[]): string {
    let p = paths
      .filter(part => !!part)
      .map(part => (part as string).trim())
      .join(Path.sep)
      .replace(/\\/g, Path.sep)
      .replace(/\//g, Path.sep);
    // p = Path.isWindows ? p.replace(/\\{2,}/g, sep) : p.replace(/\/{2,}/g, sep);
    return Path.normalize(p);
  }

  // 解析路径
  static resolve(...paths: string[]): string {
    let resolvedPath = "";
    for (const path of paths) {
      if (Path.isAbsolute(path)) {
        resolvedPath = path;
      } else {
        resolvedPath = Path.join(resolvedPath, path);
      }
    }
    return Path.normalize(resolvedPath);
  }

  // 规范化路径
  static normalize(path: string): string {
    const isAbsolute = Path.isAbsolute(path);
    const parts = path.split(/[\\/]/).filter(Boolean);
    const stack: string[] = [];

    for (const part of parts) {
      if (part === "..") {
        if (stack.length > 0 && stack[stack.length - 1] !== "..") {
          stack.pop();
        } else {
          stack.push("..");
        }
      } else if (part !== ".") {
        stack.push(part);
      }
    }

    let normalizedPath = stack.join(Path.sep);
    if (isAbsolute) {
      if (Path.isWindows && /^[A-Za-z]:[\\/]/.test(path)) {
        return normalizedPath;
      }

      normalizedPath = Path.isWindows ? `\\${normalizedPath}` : `/${normalizedPath}`;
    }
    return normalizedPath;
  }

  // 判断路径是否为绝对路径
  static isAbsolute(path: string): boolean {
    if (Path.isWindows && /^[A-Za-z]:[\\/]/.test(path)) {
      return true;
    }
    return /^\\/.test(path) || /^\//.test(path);
  }
}

/**
 * 文件路径处理器
 */
const path = Path;
export default path;
